#include <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>

#define NUM 10

typedef  void (*func_t)(); //函数指针

func_t handLerTask[NUM];

//样例任务
void task1()
{
  printf("handler task1\n");
}

void task2()
{
  printf("handler task2\n");
}

void task3()
{
  printf("handler task3\n");
}

void loadTask()
{
  memset(handLerTask,0,sizeof(handLerTask));
  handLerTask[0] = task1;
  handLerTask[1] = task2;
  handLerTask[2] = task3;
}

int main()
{
  pid_t id = fork();
  assert(id != -1);
  //子进程
  if(id == 0)
  {
    int cnt = 5;
    while(cnt)
    {
      printf("子进程在运行中，pid:%d,ppid:%d,cnt:%d\n",getpid(),getppid(),cnt--);
      sleep(1);
      
      //野指针
      // int* p = NULL;
      // *p = 100;
       
    }
    exit(10);
  }

  //加载事务
  loadTask();
  //父进程
  int status = 0;
  while(1)
  {
    pid_t ret = waitpid(id,&status,WNOHANG);
    if(ret == 0)
    {
      printf("wait done,but child is running....,parent running ohter things\n");
      int i = 0;
      for(i=0;handLerTask[i]!=NULL;i++)
      {
        //采用回调函数的方式，执行我们想让父进程在空闲时间做的事情
        handLerTask[i]();
      }
    }
    else if(ret > 0)
    {
      printf("wait success,exit code:%d,sig:%d\n",(status>>8)&0xFF,status & 0x7F);
      break;
    }
    else 
    {
      printf("waitpid call failed\n");
      break;
    }
    sleep(1);
  }

  /*
  pid_t ret = waitpid(id+1,&status,WNOHANG);
  if(ret == 0)
  {
    printf("wait done,but child is running.....,parent exit\n");
  }
  else if(ret>0)
  {
    printf("等待成功，exit code:%d,sig:%d\n",(status>>8)&0xFF,status&0x7F);
    
    
    //是否正常退出
    if(WIFEXITED(status))
    {
      //判断子进程运行结果是否正确
      printf("exit code:%d\n",WEXITSTATUS(status));
    }
    else 
    {
      printf("子进程异常退出\n");
    }
     
  }
  else 
  {
    printf("waitpid call failed\n");
  }
  */ 
  return 0;
}
